import { addPerson } from "../../api/list";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    personId: "",
    appleName: "",
    appleNumber: "",
    appleAddress: "",
    comments: "",
    photoCount: 0,
    guiGe: "",
    qty: undefined,
    opType: "",
    libType: "",
    fileList: [],
    pictures: [],
    showDetail: false,
    showSaveResult: false,
    rukus: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const _token = wx.getStorageSync("token");
    if (_token) {
      // 新建需要清空一下表单元素
      const { op, type } = options;
      if (op === "add") {
        this.setData({
          opType: op,
          appleName: "",
          appleNumber: "",
          apoleAddress: "",
          libType: type,
        });
      }
    } else {
      wx.navigateTo({
        url: "/pages/login/login",
      });
    }
  },

  uploadFile(uploadFile) {
    let token = wx.getStorageSync("token");
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        //url: "https://crm.etransfar.com/xapi/api/upload", //config.uploadUrl, // 上传的服务器接口地址
        url: "https://crm.etransfar.com/xfx/api/File/upload",
        header: {
          Authorization: `Bearer ${token}`,
        },
        filePath: uploadFile,
        name: "file", //上传的所需字段，后端提供
        success: (res) => {
          console.log("resdata=", res);
          // 上传完成操作
          // const data = JSON.parse(res.data);

          const url = res.data;
          resolve({
            url: url,
          });
        },
        fail: (err) => {
          //上传失败：修改pedding为reject
          reject(err);
        },
      });
    });
  },

  afterRead(event) {
    wx.showLoading({
      title: "上传中...",
    });
    const { file } = event.detail; //获取所需要上传的文件列表
    let uploadPromiseTask = []; //定义上传的promise任务栈

    for (let i = 0; i < file.length; i++) {
      uploadPromiseTask.push(this.uploadFile(file[i].tempFilePath)); //push进每一张所需要的上传的图片promise栈
    }
    Promise.all(uploadPromiseTask)
      .then((res) => {
        //全部上传完毕
        this.setData({
          fileList: this.data.fileList.concat(res),
        });
        wx.hideLoading();
      })
      .catch((error) => {
        //存在有上传失败的文件
        wx.hideLoading();
        wx.showToast({
          title: "上传失败！",
          icon: "none",
        });
      });
  },

  deleteImg(event) {
    const delIndex = event.detail.index;
    const { fileList } = this.data;
    fileList.splice(delIndex, 1);
    this.setData({
      fileList,
    });
  },

  openDtlDialog() {
    this.setData({
      showDetail: true,
    });
  },

  // 表单保存
  save() {
    if (!this.data.name) {
      wx.showToast({
        title: "请输入果名",
        icon: "error",
      });
      return;
    }
    let picList = [];
    for (let i = 0, iLen = this.data.fileList.length; i < iLen; i++) {
      picList.push({
        pictureUrl: this.data.fileList[i].url,
      });
    }

    let params = {
      name: this.data.name,
      kuType: this.data.libType === "cold" ? 0 : 1,
      phoneNumber: this.data.phoneNumber,
      address: this.data.address,
      pingJia: this.data.comments,
      rukus: JSON.parse(wx.getStorageSync("tempData")),
      pictures: picList,
      chukus: [],
      currentInfos: [],
    };

    addPerson(null, params)
      .then((res) => {
        this.setData({
          personId: res.data,
        });
        wx.removeStorage({
          key: "tempData",
        });
        wx.showToast({
          title: "新增成功",
          icon: "success",
        });

        // setTimeout(() => {  }, 800);
        if (this.data.libType === "cold") {
          wx.switchTab({
            url: "/pages/coldwind/coldwind",
          });
        } else {
          wx.switchTab({
            url: "/pages/qidiao/qidiao",
          });
        }
      })
      .catch((err) => {
        wx.showToast({
          title: err,
          icon: "error",
        });
      });
  },
  saveDtl() {
    // 先保存在storage
    // 主档提交一并提交
    if (this.data.guiGe && this.data.qty) {
      // let params = {
      //   personId: parseInt(this.data.personId),
      //   guiGe: this.data.guiGe,
      //   qty: parseInt(this.data.qty),
      // };

      let _tempArr = [];
      let storageArr = wx.getStorageSync("tempData");
      if (storageArr && storageArr.length > 0) {
        storageArr = JSON.parse(storageArr);
        storageArr.push({
          id: 0,
          guiGe: this.data.guiGe,
          qty: parseInt(this.data.qty),
        });
        _tempArr = JSON.stringify(storageArr);
        wx.setStorage({
          key: "tempData",
          data: JSON.stringify(storageArr),
        });
      } else {
        _tempArr.push({
          id: 0,
          guiGe: this.data.guiGe,
          qty: parseInt(this.data.qty),
        });
        wx.setStorage({
          key: "tempData",
          data: JSON.stringify(_tempArr),
        });
      }

      this.setData({
        rukus: JSON.parse(wx.getStorageSync("tempData")),
        qty: "",
        guiGe: "",
        showDetail: false,
      });

      // addDtl(null, params)
      //   .then((res) => {
      //     if (res.code === 200) {
      //       this.setData({
      //         showDetail: false,
      //         guiGe: "",
      //         qty: 0,
      //       });
      //       this.getPersonDetail();
      //     }
      //   })
      //   .catch((err) => {
      //     wx.showToast({
      //       title: "保存错误：" + err.toString(),
      //       icon: "error",
      //     });
      //   });
    } else {
      wx.showToast({
        title: "请输入规格和数量",
        icon: "error",
        zIndex: 999,
        mask: true,
      });
      return;
    }
  },
  setGuiGe(e) {
    this.setData({
      guiGe: e.detail,
    });
  },
  setQty(e) {
    this.setData({
      qty: e.detail,
    });
  },
  onClose() {
    this.setData({
      showDetail: false,
      qty: 0,
      guiGe: "",
    });
  },
  onClosePop() {
    this.setData({
      showDetail: false,
    });
  },

  // vant组件取值(果农姓名)
  setUserName(e) {
    this.setData({
      name: e.detail,
    });
  },
  // vant组件取值(果农电话)
  setPhoneNumber(e) {
    this.setData({
      phoneNumber: e.detail,
    });
  },
  // vant组件取值(果农地址)
  setAddress(e) {
    this.setData({
      address: e.detail,
    });
  },
  setComments(e) {
    this.setData({
      comments: e.detail,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.removeStorage({
      key: "tempData",
    });
  },

  deleteDtl(e) {
    let temp = wx.getStorageSync("tempData");
    if (temp && temp.length > 0) {
      temp = JSON.parse(temp);
      temp.splice(e.currentTarget.dataset.id, 1);
      wx.setStorage({
        key: "tempData",
        data: temp,
      });
      this.setData({
        rukus: temp,
      });
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
